package org.wkg.lesson08;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 自定义定时器
 * 1.创建一个任务与任务时间
 * 2.创建一个阻塞队列存储输入的任务
 * 3.调用类来存储任务
 * 4.设置线程启动任务
 *
 * @Author 比特就业课
 */


public class MyTimer_5 {
    BlockingQueue<Mytask05> queue = new PriorityBlockingQueue();

    public MyTimer_5() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Mytask05 mytask05 = queue.take();
                    if (System.currentTimeMillis() >= mytask05.getTime()) {
                        mytask05.getRunnable().run();
                    } else {
                        queue.put(mytask05);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }


    public void schedule(Runnable runnable, long time) throws InterruptedException {
        Mytask05 mytask05 = new Mytask05(runnable, time);
        queue.put(mytask05);
    }
}

class Mytask05 implements Comparable<Mytask05> {
    private Runnable runnable;
    private long time;

    public Mytask05(Runnable runnable, long delay) {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不能为null");
        }
        if (delay < 0) {
            throw new IllegalArgumentException("时间不能小于0");
        }
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(Mytask05 o) {
        //getTime是获取的哪里的数据，o.getTime是获取的哪里的数据，我有点蒙，请你由浅入深的讲解一下
        //getIime获取到的是当前传进来的数据this，而o.getTime获取的是数组中的数据，
        // 通过调用数组中的数据进行与this数据进行比较从而进行排序
        if (getTime() > o.getTime()) {
            return 1;
        } else if (getTime() < o.getTime()) {
            return -1;
        } else {
            return 0;
        }
    }
}